from pathlib import Path


class FileLineIterator:
    """文件行迭代器，自动管理文件资源"""

    def __init__(self, filename):
        self.filename = filename
        self.file = None

    def __iter__(self):
        # 打开文件
        print("这里会在什么时机执行到")
        self.file = open(self.filename, "r", encoding="utf-8")
        return self

    def __next__(self):
        if self.file is None:
            raise RuntimeError("必须先调用 __iter__ 方法")

        line = self.file.readline()
        if not line:  # 文件结束
            self.file.close()
            raise StopIteration

        return line.strip()

    def __del__(self):
        """确保文件被关闭"""
        if self.file and not self.file.closed:
            self.file.close()


# 使用示例
def process_file(filename):
    """处理文件内容"""
    filepath = Path(__file__).parent / filename
    file_line_iterator = FileLineIterator(filepath)
    # file_line_iterator.__iter__()
    # next(file_line_iterator)

    for line in file_line_iterator:
        if line:  # 跳过空行
            print(f"处理: {repr(line)}")


# 更安全的使用方式
def safe_process_file(filename):
    """更安全的文件处理方式"""
    try:
        with open(filename, "r", encoding="utf-8") as file:
            for line in file:
                line = line.strip()
                if line:
                    print(f"处理: {line}")
    except FileNotFoundError:
        print(f"文件 {filename} 不存在")
    except Exception as e:
        print(f"处理文件时出错: {e}")


# 使用
process_file("example.txt")
